import sys
parent_dir = "../pygl"
sys.path.append(parent_dir)
import ctypes
import OpenGL.GL as gl
import glm
import imgui
import numpy as np
import pygl
from common import App, AxesHelper, Cube

class CubeApp(App):
    # 初始化着色器，vao vbo等
    def setupVertex(self) -> None:
        gl.glEnable(gl.GL_DEPTH_TEST)
        self.cube = Cube(0.4, "textures/cratetex.png")
        self.cube_axes = AxesHelper(0.6, 5.0)
        self.world_axes = AxesHelper(0.9, 2.0)
        self.imgui_window_width = 250
        self.imgui_window_height = 350  
        
    # 配置imgui界面元素
    def showImGui(self)->None:
        imgui.begin("设置")
        _, self.cube.use_vertex_color = imgui.checkbox("使用顶点颜色", 
                                        self.cube.use_vertex_color)
        if imgui.button("重置"):
            self.cube.rotation = glm.vec3(0.0, 0.0, 0.0)
            self.cube.position = glm.vec3(0.0, 0.0, 0.0)
            self.cube.scale = glm.vec3(1.0, 1.0, 1.0)
        imgui.text("旋转")
        _, rot = imgui.slider_float3("R", self.cube.rotation.x, 
                    self.cube.rotation.y, self.cube.rotation.z, 0.0, 180)
        self.cube.rotation.x = rot[0]
        self.cube.rotation.y = rot[1]
        self.cube.rotation.z = rot[2]
        imgui.text("平移")
        _, trans = imgui.slider_float3("T", self.cube.position.x, 
                    self.cube.position.y, self.cube.position.z, -1.0, 1.0)
        self.cube.position = glm.vec3(trans)
        imgui.text("缩放")
        _, sc = imgui.slider_float3("S", self.cube.scale.x, self.cube.scale.y, 
                                    self.cube.scale.z, 0.2, 1.5)
        self.cube.scale = glm.vec3(sc)
        imgui.text("模型矩阵")
        imgui.begin_table("数据", 4)
        for i in range(4):
            imgui.table_next_row()
            for j in range(4):
                imgui.table_next_column()
                imgui.text(str(self.cube.model_matrix[j, i]))
        imgui.end_table()
        imgui.end()       

    # 渲染图形
    def render(self) -> None:
        gl.glClearBufferfv(gl.GL_COLOR, 0, self.background_color.to_tuple())
        gl.glClearBufferfv(gl.GL_DEPTH, 0, 1.0)

        view = glm.mat4(1.0)
        view = glm.translate(view, glm.vec3(0.0, 0.0, -3.0))
        projection = glm.mat4(1.0)
        projection = glm.perspective(glm.radians(45.0), 
                                     float(self.width)/self.height, 0.1, 100.0)
        self.cube.updateModelMatrix()
        self.cube.render(view,projection)
        self.cube_axes.model_matrix = self.cube.model_matrix
        self.cube_axes.render(view, projection)
        self.world_axes.render(view, projection)

    # 释放资源
    def cleanup(self) -> None:
        self.cube.delete()
        self.cube_axes.delete()
        self.world_axes.delete()

if __name__ == "__main__":
    app = CubeApp(100, 100, 800, 800, "你好，立方体App V1.0！")
    app.run()

